package com.shen.langchain4j.controller;

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import dev.langchain4j.community.model.dashscope.WanxImageModel;
import dev.langchain4j.data.image.Image;
import dev.langchain4j.model.output.Response;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping(value = "/image")
public class WanxImageController {
    @Autowired
    private WanxImageModel wanxImageModel;

    /**
     * 基于通义万相模型调用接口生成图片
     *
     * @return 图片URL
     */
    @GetMapping(value = "/imageCreate/one")
    public String imageCreateOne() {
        Response<Image> response = wanxImageModel.generate("生成一幅水墨画");
        log.info("[生成图片]生成图片的url为:{}", response.content().url());
        return response.content().url().toString();
    }

    /**
     * 在不构建模型配置的情况下通过dashscope依赖类生成图片
     *
     * @return 图片URL
     */
    @GetMapping(value = "/imageCreate/two")
    public String imageCreateTwo() {
        String prompt = "一副典雅庄重的对联悬挂于厅堂之中，房间是个安静古典的中式布置，桌子上放着一些青花瓷，对联上左书“义本生知人机同道善思新”，右书“通云赋智乾坤启数高志远”， 横批“智启通义”，字体飘逸，中间挂在一着一副中国风的画作，内容是岳阳楼。";
        Map<String, Object> parameters = new HashMap<>();
        parameters.put("prompt_extend", true);
        parameters.put("watermark", true);
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("aliyunQwen-apiKey"))
                        .model("qwen-image")
                        .prompt(prompt)
                        .n(1)
                        .size("1328*1328")
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            log.info("---同步调用，请等待任务执行----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e) {
            throw new RuntimeException(e.getMessage());
        }
        String jsonResult = JsonUtils.toJson(result);
        log.info(jsonResult);
        return jsonResult;
    }
}
